package at.sysarch.filter;

import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.RenderedOp;

import at.pimpmypipe.filter.DataEnrichmentFilter;
import at.sysarch.bean.AbstractBean;
import at.sysarch.domain.TransferImage;

public class ThresholdFilter extends
		DataEnrichmentFilter<TransferImage, TransferImage> {
	
	private int _lowThreshold;
	private int _highThreshold;
	private int _mapThreshold;
	
	public ThresholdFilter(AbstractBean<ThresholdFilter> bean) {
		
		super(bean);
	}

	@Override
	protected boolean fillEntity(TransferImage nextVal, TransferImage entity) {
		
		PlanarImage oldImage;
		oldImage = nextVal.getModifiedImage();	
		RenderedOp image1 = threshold(oldImage, _lowThreshold, _highThreshold, _mapThreshold);
		
//		RenderedOp whiteStep = threshold(oldImage, 0, 30, 255);
//		RenderedOp newImage = threshold(whiteStep, 0, 254, 0);
		
		entity.setModifiedImage(image1);
		entity.setSourceImage(nextVal.getSourceImage());
		
		_bean.displayImage(entity);
		return true;
	}

	@Override
	protected TransferImage getNewEntityObject() {
		return new TransferImage();
	}

	public RenderedOp threshold(RenderedImage image, int lowThreshold, int highThreshold, int mapThreshold) {
		double[] low, high, map;
		int bands = 3;
		low = new double[bands];
		high = new double[bands];
		map = new double[bands];
		for (int i = 0; i < bands; i++) {
			low[i] = lowThreshold;
			high[i] = highThreshold;
			map[i] = mapThreshold;
		}
		ParameterBlock pb = new ParameterBlock();
		pb.addSource(image);
		pb.add(low);
		pb.add(high);
		pb.add(map);
		return JAI.create("threshold", pb);
	}

	public int getLowThreshold() {
		return _lowThreshold;
	}

	public void setLowThreshold(int lowThreshold) {
		_lowThreshold = lowThreshold;
	}

	public int getHighThreshold() {
		return _highThreshold;
	}

	public void setHighThreshold(int highThreshold) {
		_highThreshold = highThreshold;
	}

	public int getMapThreshold() {
		return _mapThreshold;
	}

	public void setMapThreshold(int mapThreshold) {
		_mapThreshold = mapThreshold;
	}
}
